import { DistrictAction, DistrictActionTypes } from '../actions/districts.action';
import { District, UserLocation } from '../../../ngx-ol/models';

export interface DistrictsState {
    entities: District[];
    loaded: boolean;
    loading: boolean;
    selected: UserLocation,
    selectedLoaded: boolean,
    selectedLoading: boolean
}

export const initialDistrictsState: DistrictsState = {
    entities: [],
    loaded: false,
    loading: false,
    selected: null,
    selectedLoaded: false,
    selectedLoading: false
};

export function districtReducer(state: DistrictsState = initialDistrictsState, action: DistrictAction): DistrictsState {
    switch(action.type) {
        case DistrictActionTypes.LOAD_DISTRICTS: {
            return {
                ...state,
                loading: true
            };
        }
        case DistrictActionTypes.LOAD_DISTRICTS_FAIL: {
            return {
                ...state,
                loading: false,
                loaded: false
            };
        }
        case DistrictActionTypes.LOAD_DISTRICTS_SUCCESS: {
            const entities = action.payload;
            return {
                ...state,
                loaded: true,
                loading: false,
                entities
            }
        }
        case DistrictActionTypes.SELECT_DISTRICT: {
            return {
                ...state,
                selectedLoaded: false,
                selectedLoading: true
            };
        }
        case DistrictActionTypes.SELECT_DISTRICT_LOAD_FAIL: {
            return {
                ...state,
                selectedLoaded: false,
                selectedLoading: false
            }
        }
        case DistrictActionTypes.SELECT_DISTRICT_LOAD_SUCCESS: {
            return {
                ...state,
                selected: action.payload,
                selectedLoaded: true,
                selectedLoading: false
            }
        }
        case DistrictActionTypes.AUTO_LOCATE_DISTRICT: {
            return {
                ...state,
                selectedLoaded: false,
                selectedLoading: true
            };
        }
        case DistrictActionTypes.AUTO_LOCATE_DISTRICT_FAIL: {
            return {
                ...state,
                selectedLoaded: false,
                selectedLoading: false
            }
        }
        case DistrictActionTypes.AUTO_LOCATE_DISTRICT_SUCCESS: {
            return {
                ...state,
                selected: action.payload,
                selectedLoaded: true,
                selectedLoading: false
            }
        }
        default: {
            return state;
        }
    }
}